<template>
    <div class="car-manage">
        <!-- 条件栏 -->
        <el-card shadow="never">
            <el-form :inline="true" :model="searchForm" label-width="80px">
                <el-form-item label="汽车名称">
                    <el-input v-model="searchForm.cname" placeholder="请输入" clearable style="width: 150px;" />
                </el-form-item>

                <el-form-item label="品牌">
                    <el-select v-model="searchForm.brand" placeholder="全部" clearable
                        style="width: 150px;margin-left: 0;">
                        <el-option label="奔驰" value="奔驰" />
                        <el-option label="宝马" value="宝马" />
                        <el-option label="保时捷" value="保时捷" />
                        <el-option label="比亚迪" value="比亚迪" />
                        <el-option label="宾利" value="宾利" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-input-number v-model="searchForm.dailyRate" :precision="2" :min="0" :step="0.01"
                        placeholder="单日租金" clearable style="width:160px" />
                </el-form-item>

                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 150px;">
                        <el-option label="全部" :value="undefined" />
                        <el-option label="正常" :value="0" />
                        <el-option label="已下架" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">
                        查询
                    </el-button>
                    <el-button :icon="Plus" type="success" @click="handleAdd">
                        新增
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据表格 -->
        <el-card shadow="never" style="margin-top:12px">
            <el-table :data="tableData" stripe v-loading="loading" border :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column prop="cid" label="ID" width="100" />
                <el-table-column prop="cname" label="名称" min-width="120" />

                <el-table-column label="图片" width="150" align="center">
                    <template #default="{ row }">
                        <el-image :src="row.photo" fit="cover" style="width:80px;height:50px;border-radius:4px"
                            :preview-src-list="[row.photo]" :z-index="2000" />
                    </template>
                </el-table-column>

                <el-table-column prop="brand" label="品牌" width="150" />
                <el-table-column prop="model" label="型号" width="150" />

                <el-table-column prop="dailyRate" label="单日租金(元)" width="110">
                    <template #default="{ row }">
                        <span style="color:#f56c6c;font-weight:600">
                            {{ row.dailyRate }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="count" label="库存(辆)" width="90" />

                <el-table-column label="状态" width="90" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 0 ? 'success' : 'info'">
                            {{ row.status === 0 ? '在售' : '不售' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" width="170" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleEdit(row)">修改</el-button>
                        <el-popconfirm title="确定更改吗？" @confirm="handleDelete(row)">
                            <template #reference>
                                <el-button size="small" type="danger">下架</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="margin-top:12px;text-align:right">
                <el-pagination background layout="prev, pager, next, jumper, ->, total"
                    :current-page="pageParam.pageNum" :page-size="pageParam.pageSize" :total="pageParam.total"
                    @current-change="changePage" />
            </div>
        </el-card>
    </div>

    <div>
        <!-- 修改/新增汽车弹窗 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="30%" draggable>
            <el-form label-width="90px" :model="dialog.car" class="demo-form-inline">
                <!-- 1. 汽车名称 -->
                <el-form-item label="汽车名称">
                    <el-input v-model="dialog.car.cname" placeholder="请输入名称" clearable style="width:160px" />
                </el-form-item>

                <!-- 2. 品牌 -->
                <el-form-item label="品牌">
                    <el-select v-model="dialog.car.brand" placeholder="请选择品牌" clearable style="width:160px">
                        <el-option label="奔驰" value="奔驰" />
                        <el-option label="宝马" value="宝马" />
                        <el-option label="保时捷" value="保时捷" />
                        <el-option label="比亚迪" value="比亚迪" />
                        <el-option label="宾利" value="宾利" />
                    </el-select>
                </el-form-item>

                <!-- 3. 型号 -->
                <el-form-item label="型号">
                    <el-input v-model="dialog.car.model" placeholder="如:C200L" clearable style="width:160px" />
                </el-form-item>

                <!-- 4. 单日租金 -->
                <el-form-item label="单日租金">
                    <el-input-number v-model="dialog.car.dailyRate" :min="0" :precision="2" :step="0.01"
                        controls-position="right" style="width:40%" />
                </el-form-item>

                <!-- 5. 库存数量 -->
                <el-form-item label="库存数量">
                    <el-input-number v-model="dialog.car.count" :min="0" :step="1" controls-position="right"
                        style="width:40%" />
                </el-form-item>

                <!-- 6. 车辆状态 -->
                <el-form-item label="车辆状态">
                    <el-radio-group v-model="dialog.car.status">
                        <el-radio :label="0">正常（在售）</el-radio>
                        <el-radio :label="1">已下架（不售）</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 7. 图片显示 / 上传（放在最下方） -->
                <el-form-item label="车辆图片">
                    <div style="
          width: 160px;
          height: 100px;
          background: #fafafa;
          border-radius: 6px;
          overflow: hidden;
          cursor: pointer;
        " @click="showUploadImageDialog">
                        <el-image v-if="dialog.car.photo" :src="dialog.car.photo" fit="cover"
                            style="width:100%;height:100%;" />
                        <div v-else style="
            width:100%;
            height:100%;
            display:flex;
            align-items:center;
            justify-content:center;
            color:#909399;
            font-size:12px;
          ">
                            点击上传
                        </div>
                    </div>
                </el-form-item>

                <!-- 8. 底部按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="insertAndUpdateCar">
                        {{ dialog.btnText }}
                    </el-button>
                    <el-button @click="dialog.visible = false">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <!-- 上传头像对话框 -->
    <div>
        <!-- 修改对话框 -->
        <el-dialog v-model="uploadDialog.visible" title="文件上传" width="30%" draggable>
            <el-upload :action="uploadDialog.uploadUrl" list-type="picture-card" :file-list="fileList"
                :limit="uploadDialog.limit" :auto-upload="uploadDialog.autoUpload" :on-change="handlerImage">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <!-- 添加上传按钮 -->
            <el-form-item style="margin-top: 10px;margin-left: 320px;">
                <el-button type="primary" @click="uploadHandler()">上传</el-button>
            </el-form-item>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
//定义对话框属性
let dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    car: {
        cid: '',
        cname: '',
        brand: '',
        model: '',
        dailyRate: 0,
        count: 0,
        status: 0,      // 0 正常  1 下架
        photo: ''
    }
})
//定义变量控制文件上传
const uploadDialog = reactive({
    visible: false, //隐藏对话框
    uploadUrl: "",
    fileList: [], //保存所有上传文件集合
    limit: 1,//控制文件上传个数
    autoUpload: false,
    uploadFile: null,
})
//实现文件上传函数
const uploadHandler = async () => {
    //文件上传详细步骤
    //1.创建FormData对象
    let formData = new FormData();
    //2.设置上传对象对象
    formData.append("file", uploadDialog.uploadFile)
    //3.设置上传类型
    let contentType = { "ContentType": "multipart/form-data" }
    formData.append("headers", contentType);
    //4.发送请求实现文件上传
    let res = await request.post("/user/fileUpload", formData);
    // console.log(res.data);
    if (res.data.success) {
        //把上传文件保存到表单imgPath中
        dialog.value.car.photo = res.data.data; //http://localhost:80/xxxx.png
        //显示提示信息
        ElMessage.success("上传成功");
        //关闭文件上传对话框
        uploadDialog.visible = false;
    }
}

//选中文件时触发函数
const handlerImage = (file) => {
    uploadDialog.uploadFile = file.raw;
}
//显示文件上传对话框
const showUploadImageDialog = () => {
    uploadDialog.visible = true;
}

//显示修改汽车对话框
const handleEdit = (row) => {
    //显示表单信息
    Object.assign(dialog.value.car, row);
    //设置对话框标题
    dialog.value.title = "修改汽车";
    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
}
//显示新增汽车对话框
const handleAdd = () => {
    //清空对话框信息
    dialog.value.car = {
        cid: '',
        cname: '',
        brand: '',
        model: '',
        dailyRate: 0,
        count: 0,
        status: 0,      // 0 正常  1 下架
        photo: ''
    }
    //设置对话框标题
    dialog.value.title = "新增汽车";
    //设置按钮文本内容
    dialog.value.btnText = "新增";
    //显示对话框
    dialog.value.visible = true;
}

//实现汽车修改、新增操作
const insertAndUpdateCar = async () => {
    // console.log(dialog.value.car); //查询是否有值
    let res = await request.put("/car/saveOrUpdate", dialog.value.car);
    //判断新增成功
    if (res.data.success) {
        //1,清空对话框
        dialog.value.car = {
            cid: '',
            cname: '',
            brand: '',
            model: '',
            dailyRate: 0,
            count: 0,
            status: 0,      // 0 正常  1 下架
            photo: ''
        }
        //2.刷新页面
        fetchTable();
        //3.显示提示信息
        ElMessage.success("操作成功")
        //4.关闭对话框
        dialog.value.visible = false;
    } else {
        ElMessage.error(res.data.message);
        //4.关闭对话框
        dialog.value.visible = false;
    }
}
//下架操作
const handleDelete =async (row)=>{
    let res = await request.put('/car/delete',{id:row.cid});
    if(res.data.success){
        fetchTable();
        ElMessage.success('操作成功');
    }else{
        ElMessage.error(res.data.message);
    }
}
/* 搜索条件 */
const searchForm = reactive({
    cname: '',
    brand: '',
    status: undefined,   // 查全部就传 undefined
})

/* 分页参数 */
const pageParam = reactive({
    pageNum: 1,
    pageSize: 5,
    total: 0
})

/* 表格数据 */
const tableData = ref([])
const loading = ref(false)

/* 统一拉取列表 */
const fetchTable = async () => {
    loading.value = true
    try {
        const { data: res } = await request.post('/car/queryCondition', {
            ...searchForm,          // 这里已包含 status
            pageNum: pageParam.pageNum,
            pageSize: pageParam.pageSize
        })
        if (res.success) {
            tableData.value = res.data.list
            pageParam.total = res.data.total
        } else {
            ElMessage.error(res.msg || '获取列表失败')
        }
    } finally {
        loading.value = false
    }
}
/* 搜索按钮 */
const handleSearch = () => {
    pageParam.pageNum = 1
    fetchTable()
}

/* 分页切换 */
const changePage = (p) => {
    pageParam.pageNum = p
    fetchTable()
}


onMounted(() => {
    fetchTable()
})
</script>
<style scoped></style>